import { forwardRef, useEffect, useState, useImperativeHandle } from "react";

import { getCaptcha } from "@/api/login";

import style from "./index.module.scss";

const Captcha = forwardRef((_, ref) => {
  const [captchaId, setCaptchaId] = useState("");
  const [svg, setSvg] = useState("");

  function refresh() {
    // 调用接口
    getCaptcha().then((resp) => {
      setCaptchaId(resp.captchaId);
      setSvg(resp.data);
    });
  }

  useImperativeHandle(
    ref,
    () => ({
      get() {
        return captchaId;
      },
      refresh,
    }),
    [captchaId]
  );

  useEffect(() => {
    refresh();
  }, []);

  return (
    <div
      className={style.box}
      dangerouslySetInnerHTML={{ __html: svg }}
      onClick={refresh}
    />
  );
});

// 对外的类型， get， resfresh 类型提供出去
export type CaptchaInstance = {
  get: () => string;
  refresh: () => void;
};

export default Captcha;
